import * as pdfjsLib from 'pdfjs-dist'
pdfjsLib.GlobalWorkerOptions.workerSrc = '/public/pdf.worker.min.mjs'


const getPdfPageBlobUrls = async (arrayBuffer: ArrayBuffer, { scale = 1.0, coverPageNum = 1 } = {}) => {
  try {
    const pdfDoc = await pdfjsLib.getDocument(arrayBuffer).promise     // 加载PDF文档
    const page = await pdfDoc.getPage(coverPageNum) // 获取页面
    const viewport = page.getViewport({ scale }) // 设置视图大小
    // 创建Canvas元素
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = viewport.width
    canvas.height = viewport.height

    // 渲染页面到Canvas
    if (context) {
      await page.render({ canvasContext: context, viewport: viewport, canvas }).promise
    } else {
      throw new Error('无法获取Canvas上下文')
    }

    const url = canvas.toDataURL('image/png')  // 将Canvas转换为dataUrl

    page.cleanup() // 清理内存
    pdfDoc.destroy() // 销毁PDF文档对象

    return url
  } catch (error) {
    console.error('获取PDF页面Blob失败:', error)
    throw new Error('PDF封面加载失败')
  }
}

export default async (arrayBuffer: ArrayBuffer) => await getPdfPageBlobUrls(arrayBuffer, { scale: 1.0 })
